<!-- 厂区下拉框 -->
<template>
  <px-form-item
    :label="customLabel || '厂区'"
    :prop="props.propValue ? props.propValue : 'factoryArea'"
    :rules="{ required: props.isRequired, message: '厂区不能为空', trigger: ['blur', 'change'] }"
  >
    <px-select
      v-model="factoryVal"
      :disabled="props.isDisabled"
      :clearable="clearable"
      filterable
      placeholder="请选择厂区"
      style="width: 100%"
      @focus="focusFactory"
      @change="changeFactory"
      @clear="clear"
    >
      <px-option v-for="item in factoryList" :key="item.id" :label="item.name" :value="item.value" />
    </px-select>
  </px-form-item>
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { computed, ref, watch } from "vue";

// 父级方法和值
const emits = defineEmits(["changeFactory", "clear"]);
const props = defineProps(["facCode", "isRequired", "propValue", "isDisabled", "clearable", "customLabel"]);

const factoryVal = ref("");
const factoryList = ref([]);
const clearable = computed(() => {
  if (props.clearable === false) {
    return false;
  }
  return clearable;
});
watch(
  () => props.facCode,
  val => {
    factoryVal.value = props.facCode;
    if (val) {
      setTimeout(() => {
        focusFactory();
      }, 0);
    }
  },
  { immediate: true }
);
// 获取工厂下拉列表
const focusFactory = async () => {
  const tempFactoryList = await queryDictData({ typeCode: "factoryArea" });
  factoryList.value = tempFactoryList || [];
};
// 改变工厂值，传值给父级并做改变
const changeFactory = () => {
  emits("changeFactory", factoryVal.value);
};
const clear = () => {
  emits("clear", factoryVal.value);
};
</script>
